package com.ruoyi.alert.service;

import com.alibaba.nacos.common.codec.Base64;
import com.ruoyi.alert.domain.Alert;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


@Service
public class DingTalkService {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkService.class);

    @Value("${dingtalk.webhook}")
    private String webhookUrl;

    @Value("${dingtalk.secret}")
    private String secret;

    private String generateSign(long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }

    public void sendAlarm(Alert msg) {
        try {

            long timestamp = System.currentTimeMillis();
            String sign = generateSign(timestamp);

            // 构建带签名的URL
            String signedUrl = webhookUrl + "&timestamp=" + timestamp + "&sign=" + sign;

            String message = String.format(
                    "### COD异常报警\n**项目部**: %s\n**日期**: %tF\n**波动值**: %.2f mg/L",
                    msg.getProjectName(), msg.getDate(), msg.getDiffValue()
            );

            String jsonPayload = String.format(
                    "{\"msgtype\":\"markdown\",\"markdown\":{\"title\":\"废水处理报警\",\"text\":\"%s\"}}",
                    message
            );

            logger.info("准备发送钉钉消息，内容: {}", jsonPayload);

            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(signedUrl);
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setEntity(new StringEntity(jsonPayload, "UTF-8"));

                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    logger.info("钉钉返回状态: {}", response.getStatusLine());
                    String responseBody = EntityUtils.toString(response.getEntity());
                    logger.info("钉钉返回内容: {}", responseBody);
                }
            }
        } catch (Exception e) {
            logger.error("发送钉钉消息失败", e);
            throw new RuntimeException("发送钉钉消息失败", e);
        }
    }
}